package cn.gbase.jiangsu.data.transfer.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.DaoException;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Scope;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.CommunityService;
import cn.gbase.jiangsu.data.transfer.bean.CompanyUser;
import cn.gbase.jiangsu.data.transfer.bean.ProductSortTree;
import cn.gbase.jiangsu.data.transfer.bean.ProductSortTreeNode;
import cn.gbase.jiangsu.data.transfer.common.SystemException;
import cn.gbase.jiangsu.data.transfer.service.ProductSortTreeNodeService;
import cn.gbase.jiangsu.data.transfer.util.PropertyFilter;
import cn.gbase.jiangsu.data.transfer.util.SystemContext;

@IocBean(args = { "refer:dao" })
@At("/communityService")
public class CommunityServiceAction extends IdEntityService<CommunityService> {
	public CommunityServiceAction() {
		super();
	}

	public CommunityServiceAction(Dao dao) {
		super(dao);
	}

	@Inject
	private ProductSortTreeNodeService productSortTreeNodeService;

	/**
	 * 服务预处理
	 * @param commentId  评论ID
	 * @return
	 */
	@At("/preCommunityService")
	@Ok("jsp:/communityService/input")
	public Object preCommunityService(@Param("p") int pageNum, @Param("numPerPage") int numPerPage,
			HttpServletRequest request,
			@Attr(scope = Scope.SESSION, value = SystemContext.COMPANYUSER) CompanyUser companyUser) {
		ProductSortTree productSortTree = this.dao().fetch(ProductSortTree.class,
				Cnd.where("company_id", "=", companyUser.getCompanyId()));
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		Cnd cnd = PropertyFilter.toCnd(filters, "id", "DESC");
		//cnd.and("create_user_id", "=", user.getUserId() + "");
		cnd.and("treeId", "=", productSortTree.getId());
		cnd.and("pid", ">",0);
		Pager pager = this.dao().createPager((pageNum < 1) ? 1 : pageNum,
				(numPerPage < 1) ? SystemContext.PAGE_SIZE : numPerPage);
		List<ProductSortTreeNode> list = this.dao().query(ProductSortTreeNode.class, cnd, pager);
		if (pager != null) {
			pager.setRecordCount(this.dao().count(ProductSortTreeNode.class, cnd));
		}
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("treeId", productSortTree.getId() + "");
		itemMap.put("treeName", productSortTree.getName());
		request.setAttribute("formdata", itemMap);
		return new QueryResult(list, pager);
	}

	//读取当前物业公司的楼盘列表
	/*@At("/listCommunityService")
	@Ok("jsp:/communityService/listCommunityService")
	public Object list(@Param("p") int pageNum, @Param("numPerPage") int numPerPage, HttpServletRequest request,
			@Attr(scope = Scope.SESSION, value = SystemContext.COMPANYUSER) CompanyUser companyUser) {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		Cnd cnd = PropertyFilter.toCnd(filters, "id", "DESC");
		cnd.and("company_id", "=", companyUser.getCompanyId());
		Pager pager = this.dao().createPager((pageNum < 1) ? 1 : pageNum,
				(numPerPage < 1) ? SystemContext.PAGE_SIZE : numPerPage);
		List<Community> list = this.dao().query(Community.class, cnd, pager);
		if (pager != null) {
			pager.setRecordCount(this.dao().count(Community.class, cnd));
		}
		return new QueryResult(list, pager);
	}*/

	@At("/addNode/?")
	@Ok("jsp:/communityService/addNode")
	public void toAddPage(String treeId, HttpServletRequest request, HttpSession session,
			@Attr(scope = Scope.SESSION, value = SystemContext.COMPANYUSER) CompanyUser companyUser) {

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("treeId", treeId);
		request.setAttribute("formdata", itemMap);

		// 回传表单输入
		Map<String, String> listMap = new HashMap<String, String>();
		listMap.put("pid", createTreeItems(Integer.parseInt(treeId)));
		session.setAttribute("listdata", listMap);

	}

	private String createTreeItems(int treeId) {
		StringBuilder builder = new StringBuilder();
		builder.append("<option value='0'>请选择..</option>");
		builder.append(productSortTreeNodeService.getTreePulldownList(treeId));
		return builder.toString();
	}

	@At("/saveTreeNode")
	@Ok("jsp:/communityService/addNode")
	public Object saveTreeNode(@Param("..") ProductSortTreeNode node, HttpServletRequest request,
			@Attr(scope = Scope.SESSION, value = SystemContext.COMPANYUSER) CompanyUser companyUser) {
		try {
			/*ProductSortTree productSortTree = this.dao().fetch(ProductSortTree.class,
					Cnd.where("company_id", "=", companyUser.getCompanyId()));
			node.setCreateUser(companyUser.getId() + "");*/
			productSortTreeNodeService.addOrUpdStandTreeNode(node);
		} catch (DaoException e) {
			if (e.getCause() instanceof SystemException) {
				request.setAttribute("errmsg", e.getCause().getMessage());
			} else {
				request.setAttribute("errmsg", e.getMessage());
			}
			request.setAttribute("formdata", node); // 表单数据
			throw e;
		}
		request.setAttribute("message", "操作成功");
		return node;
	}

	@At("/findCommunityServiceTree/?")
	public String findCommunityServiceTree(String comunityId) {
		ProductSortTree productSortTree = this.dao().fetch(ProductSortTree.class,
				Cnd.where("community_id", "=", comunityId).and("name", "like", "%物业服务%"));
		if (productSortTree == null) {
			return "0";
		} else {
			return "1";
		}
	}

	@At("/editNode/?")
	@Ok("jsp:/communityService/updateNode")
	public void toEditPage(@Param("nodeId") int nodeId, HttpServletRequest request, HttpSession session) {

		// 取得用户数据，放入表单中
		ProductSortTreeNode node = productSortTreeNodeService.getStandTreeNode(nodeId);
		request.setAttribute("formdata", node);

		ProductSortTreeNode productSortTreeNode = this.dao().fetch(ProductSortTreeNode.class, nodeId);
		ProductSortTree productSortTree = this.dao().fetch(ProductSortTree.class, productSortTreeNode.getTreeId());

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("pid", createTreeItems(node.getTreeId()));

		request.setAttribute("comunityId", productSortTree.getCompanyId() + "");

		session.setAttribute("listdata", itemMap);
	}

	@At("/deleteNode/?")
	public void delete(int nodeId) {
		productSortTreeNodeService.deleteStandTreeNode(nodeId);
	}

	/**
	 * 跳转到添加服务页面（服务管理）.
	 */
	@At("/toAddCommunityService")
	@Ok("jsp:/communityService/serviceInput")
	public void toAddCommunityService(HttpServletRequest req) {

	}
}
